/**
 * 订单模块：选择收货地址、支付方式、配送方式，使用优惠券、礼品卡、账户余额
 */
define('module/orderJoin', function (require, exports, module){
  'use strict';

  var user = require('user'),
          common = require('common');

  var order;
  order = {
    total_price: 0, //订单商品总价格
    init_price: 0, //订单初始价格
    total_delivery: 0, //订单总运费
    sub_price: 0, //小计
    realname: 0,
    /*订单初始化*/
    init: function (total_price,realname) {
      var _self = this;
      _self.selectAddress();
      _self.selectOption();
      _self.total_price = _self.init_price = total_price;
      _self.selectDelivery();
      _self.realname = realname;
      //配送方式改变
      $('.J_delivery_id').on('change', function () {
        _self.selectDelivery();
      });
      $('#J_order_submit').on('click', function () {
        var ok = $('#J_button').val();
        if(ok == 1){
          $.ui.alert('请尝试更换收货地址，选择有货的地区');
          return false;
        }
        _self.submit(realname);
      });
    },
    /*选择收货地址*/
    selectAddress: function () {
      var _self = this,
          item = $('.J_address_item');
      item.on('click', function () {
        $(this).addClass('selected').siblings().removeClass('selected');
        $(this).find('.J_receiver_id').prop('checked', !0);
        $(this).siblings().find('.J_receiver_id').prop('checked', !1);
        _self.setAddrState();
      });
    },

    /*设置选中状态*/
    selectOption: function () {
      $('#J_order_pay .item, #J_order_delivery .item').on('click', function () {
        $(this).addClass('selected').children('input').prop('checked', !0);
        $(this).siblings().removeClass('selected');
      });
    },
    /*选择配送方式*/
    selectDelivery: function () {
      var _self = this,
          price = 0;   
      price = $('#J_delivery_fee').attr('data-fee');
      _self.getZonePrice();
      _self.total_delivery = price;
      if(_self.init_price == 0)price = _self.total_delivery = 0;
      $('#J_delivery_fee').html(parseFloat(price).toFixed(2) + ' 元');
        $('#J_delivery_fee_count').val(parseFloat(price).toFixed(2));
      _self.countTotalPrice();
    },
    /*设置收货地址状态*/
    setAddrState: function (state) {
      if (state === '1') {
        $('#addrState').val(state);
      } else {
        var checkbox = $('#J_address_list').find('.selected'),
            isnew = checkbox.attr('data-isnew');
        $('#addrState').val('true' === isnew ? '1' : '0')
      }
      this.getdelivery();
    },
    /*统计购物车使用某一种支付方式后的剩余金额*/
    countSubPrice: function () {
      this.sub_price = parseFloat(this.init_price) + parseFloat(this.total_delivery);
      if (this.sub_price <= 0) {
        this.sub_price = 0;
      }
      return (this.sub_price).toFixed(2);
    },
    /*统计购物车商品总价格=商品总价格 + 运费*/
    countTotalPrice: function () {
      var t_price = $('#J_total_amount').attr('data-price');
        this.total_price = parseFloat(t_price)+ parseFloat(this.total_delivery);
      if (this.total_price <= 0) {
        this.total_price = 0;
      } 
      $('#J_total_price').html((this.total_price).toFixed(2));
    },
    /*获取收货地址*/
    getdelivery:function () {
      var _self = this;
      var city_id=$('#J_address_list').find('.selected').attr('data-city');
      var district_id=$('#J_address_list').find('.selected').attr('data-district');
      var province_id=$('#J_address_list').find('.selected').attr('data-province');
      var _data={'city':city_id,'district':district_id,'province':province_id};
      $.ajax({
        type:'POST',
        url:$.U('Join/getDeliveryByArea'),
        data:_data,
        dataType:'json',
        success:function (res) {
          if(res.status==1){
            var fee = res.delivery_fee;
            $('#J_delivery_fee').html(fee+'元');
            $('#J_delivery_fee').attr('data-fee',fee);
            _self.selectDelivery(); 
          }
        }
      })

    },
    /*根据配送地址处理区域价格*/
    getZonePrice:function(){
      var city=$('#J_address_list').find('.selected').attr('data-city');
      if(!city)return false;
      var _self = this;
      var items = $('input[name="item_ids"]').val();
      var buy = $('input[name="buynowss"]').val();
      $.ajax({
        type:'POST',
        url:$.U('Item/handle_zoneprice'),
        data:{'city':city, 'item_ids' : items, 'buy': buy},
        async:false,
        dataType:'json',
        success:function (res) {
          var totals = 0;var num = 0;
          if(res.status == 3){
            return false;
          }else if(res.status == 2){
            $.ui.alert('该地区暂时无货！');
            $.each(res.goods ,function(key , val){
              var items = '.item.item_'+val.item_id+'_'+val.item_code;
              $(items).removeClass('zone_out');
              var danjia = 0;
              var shu    = 0;
              if(!val.zone_out){
                danjia = val.price * 1;
                shu    = val.quantity * 1;
              }else{
                $(items).addClass('zone_out');
              }
              num     += shu * 1;
              totals  += danjia * shu;
              var zongjia  = danjia * shu;
              $(items).find('.danjia').html('<em class="yen">&yen;</em>'+ danjia.toFixed(2));
              $(items).find('.zongjia').html('<em class="yen">&yen;</em>'+ zongjia.toFixed(2));
              //无货显示
              $('#J_order_submit').css({'border-color':'#666','background-color':'#666'}).attr('href','javascript:void(0);');
              $('#submitAddress').next().removeAttr('id');
              $('#J_button').val(1);
              $('#J_total_amount').attr('data-price',zongjia.toFixed(2));//商品总价
              $('#J_total_amount').html(zongjia.toFixed(2) + ' 元');//商品总价
              $('#J_delivery_fee').attr('data-fee','0.00');//设置运费
              var tot = totals;
              $('#J_total_price').html(tot + ' 元');//应付金额
              _self.init_price = tot;
            });
          }else if(res.status == 1){
            $.each(res.goods ,function(key , val){
              var items = '.item.item_'+val.item_id+'_'+val.item_code;
              $(items).removeClass('zone_out');
              var danjia = 0;
              var shu    = 0;
              // if(!val.zone_out){
                danjia = val.price * 1;
                shu    = val.quantity * 1;
              // }
              num     += shu * 1;
              totals  += danjia * shu;
              var zongjia  = danjia * shu;
              $(items).find('.danjia').html('<em class="yen">&yen;</em>'+ danjia.toFixed(2));
              $(items).find('.zongjia').html('<em class="yen">&yen;</em>'+ zongjia.toFixed(2));
              //有货显示
              $('#submitAddress').next().css({'border-color':'#2d8701','background-color':'#2d8701'});
              $('#submitAddress').next().attr('id','J_order_submit');
              $('#J_button').val(0);
              $('#J_total_amount').attr('data-price',zongjia.toFixed(2));//商品总价
              $('#J_total_amount').html(zongjia.toFixed(2) + ' 元');//商品总价
              var fees = $('#J_delivery_fee').attr('data-fee');
              var tot = totals + fees;
              $('#J_total_price').html(tot + ' 元');//应付金额
              _self.init_price = tot;
            });
          }
          
        }
      })
    },
    /*提交订单*/
    submit: function (realname) {
      var receiver_id = $('input[type="radio"][name="receiver_id"]:checked').val();
      var item_ids = $('#J_item_ids').val();
      if(realname == 1){
         var rname  = $('.rname').val();
         var idcard = $('.idcard').val();
        if (rname == null ||rname == '' ) {
          $.ui.error('请完善实名信息备案，填写真实姓名');
          return false;
        }
        if (idcard == null || idcard == '') {
          $.ui.error('请完善实名信息备案，填写身份证号');
          return false;
        }
        if(!checkname(rname)){
          $.ui.error('请填写正确的名字');
          return false;
        }
        if(!IdCardValidate(idcard)){
          $.ui.error('请填写真实的身份证号码');
          return false;
         }
        
      }
      //验证订单商品
      if (item_ids == null || item_ids == '') {
        $.ui.error('订单商品为空！');
        return false;
      }
      //验证收货地址
      if (receiver_id == null || receiver_id == '') {
        $.ui.error('请您选择收货地址！');
        return false;
      }
      $('#J_checkout_form').submit();
    },
    /*选取支付方式*/
    selectPayment: function () {
      $('.J_payment_type').on('click', function () {
        $('#J_third_pay li').removeClass('active').find('input[type="radio"]').prop('checked', !1);
        $(this).addClass('active').find('input[type="radio"]').prop('checked', 1);
      });
      $('input[name="payment_type"]').on('click', function () {
        $('input[name="bank_name"]').prop('checked', !1);
      });
      $('input[name="bank_name"]').on('click', function () {
        $('input[name="payment_type"]').prop('checked', !1);
      });
    },
    /*执行支付*/
    pay: function (order_id) {
      $('#J_payment_' + order_id).on('submit', function () {
        var paymeny_type = $('input[name="payment_type"]:checked').val();
        if (paymeny_type === 'wechatpay') {
          var order_id = $('input[name="order_id"]').val();
          $.ui.load($.U('/Pay/weixinPayCode', 'order_id=' + order_id), '请用微信扫码支付');
          return false;
        } else {
          var pay_redirect = function () {
            window.location.href = $.U('Member/order');
          }
          $.ui.confirm('是否支付成功？', pay_redirect);
        }
      });
    },
    /*PC端微信支付*/
    weixinPay: function (order_id) {
      var get_pay_status = function () {
        if ($('#J_weixinpay_qrcode').size() === 0) {
          return false;
        }
        $.ajax({
          type: 'GET',
          url: $.U('Pay/weixinPayCode'),
          data: {order_id: order_id, get_status: 1},
          dataType: 'json',
          success: function (res) {
            if (res.status === 1) {
              $('#J_load_box').remove();
              $.ui.success(res.info);
              if (res.url) {
                common.redirect(res.url);
              } else {
                common.reload();
              }
            } else {
              setTimeout(function () {
                get_pay_status();
              }, 1000);
            }
          }
        });
      };
      get_pay_status();
    },
    /*发送手机余额支付验证码*/
    send_paymobilecode: function (obj_base, send_type, mobile) {
      var button = $('.' + obj_base + '_button');
      var code = $('.' + obj_base + '_randcode');
      var lazytime = 120;
      var time_;
      var get_time = function () {
        var expires = new Date();
        return parseInt(expires.getTime() / 1000);
      };
      var wait_fun = function () {
        clearInterval(time_);
        button.data('showonly', 1).attr('disabled', true);
        var _fun = function () {
          if (lazytime > 0) {
            var msg = lazytime + ' 秒后重新发送';
            button.html(msg);
            lazytime--;
          } else {
            button.html('重发验证码').data('showonly', 0).attr('disabled', false);
            clearInterval(time_);
          }
        };
        return setInterval(_fun, 1000);
      };
      var ovtime = $.cookies.get('mobile_code_' + send_type + '_' + mobile);
      if (ovtime) {
        lazytime = ovtime - get_time();
        if (lazytime > 0) {
          wait_fun(lazytime);
        }
      }
      //发送按钮
      button.click(function () {
        if ($(this).data('showonly') === 1) {
          return;
        }
        button.html('验证码发送中…').data('showonly', 1).attr('disabled', true);
        $.post($.U('/User/sendMobileCode'), {"mobile": mobile, send_type: send_type}, function (json) {
          if (json.code == 200) {
            $.cookies.set('mobile_code_' + send_type + '_' + mobile, get_time() + json.over_sec);
            if (json.send_new === 1) {
              $.ui.success(json.msg);
            }
            lazytime = json.over_sec;
            //重新发送倒计时
            time_ = wait_fun();
            code.focus();
          } else {
            $.ui.error(json.msg);
            button.html('发送验证码').data('showonly', 0).attr('disabled', false);
          }
        }, 'json');
      });
    },
    /*快速支付，非第三方支付*/
    quickPay: function (order_id) {
      var randcode = $('.J_mobile_randcode'),
          randcode_val = randcode.val();
      if (randcode_val == null || randcode_val == '') {
        $.ui.error('请您输入支付验证码');
        randcode.focus();
        return false;
      }
      $('#J_payment_' + order_id).submit();
    },
    /*修改订单状态*/
    setStatus: function (order_id, type) {
      var text = {'cancel': '取消', 'recycle': '删除', 'delete': '永久删除', 'restore': '还原'};
      $.ui.confirm('您确定' + text[type] + '该订单？', function () {
        $.ajax({
          type: 'POST',
          url: $.U('Order/setStatus'),
          data: {'order_id': order_id, 'type': type},
          dataType: 'json',
          success: function (res) {
            if (res.status == 1) {
              $.ui.success(res.info);
              common.reload();
            } else {
              $.ui.error(res.info);
            }
          }
        });
      });
    },
    /*确认收货*/
    confirm: function (order_id) {
      $.ui.confirm('您确认已收货？', function () {
        $.ajax({
          type: 'POST',
          url: $.U('Order/confirm'),
          data: {'order_id': order_id},
          dataType: 'json',
          success: function (res) {
            if (res.status == 1) {
              $.ui.success(res.info);
              common.reload();
            } else {
              $.ui.error(res.info);
            }
          }
        });
      });
    },
    /*申请退款*/
    refund: function (order_id) {
      $.ui.confirm('您确定申请退货/退款？', function () {
        $.ajax({
          type: 'POST',
          url: $.U('Order/refund'),
          data: {order_id: order_id},
          dataType: 'json',
          success: function (res) {
            if (res.status === 1) {
              $.ui.success(res.info);
              common.reload();
            } else {
              $.ui.error(res.info);
            }
          }
        });
      });
    },
    /*取消退款*/
    unrefund: function (order_id) {
      $.ui.confirm('您确定撤销退款申请？', function () {
        $.ajax({
          type: 'POST',
          url: $.U('Order/unrefund'),
          data: {order_id: order_id},
          dataType: 'json',
          success: function (res) {
            if (res.status === 1) {
              $.ui.success(res.info);
              common.reload();
            } else {
              $.ui.error(res.info);
            }
          }
        });
      });
    },
    /*退货信息提交*/
    reShip: function (order_id) {
      var company_name = $("select[name='company_name']").val();
      var ship_number = $("input[name='ship_number']").val();
      if (company_name.length < 2) {
        $.ui.alert('请输入快递公司名称！');
        $("input[name='company_name']").focus();
        return;
      }
      if (ship_number.length < 5) {
        $.ui.alert('请输入快递单号！');
        $("input[name='ship_number']").focus();
        return;
      }
      $.ajax({
        type: 'POST',
        url: $.U('Order/reShip'),
        data: {order_id: order_id, company_name: company_name, ship_number: ship_number},
        dataType: 'json',
        success: function (res) {
          $.ui.alert(res.info);
          if (res.status === 1) {
            common.reload();
          }
        }
      });
    },
    /*提醒发货*/
    notice: function (order_id) {
      $.ui.success('提醒成功');
    },
    /*设置提示信息*/
    setMsg: function (a, b) {
      b ? a.html(b).show() : a.html('').hide();
    },
    listsBind: function () {
      var _self = this;
      $('.J_order_confirm').on('click', function () {
        var id = $(this).data('id');
        _self.confirm(id);
      });
      $('.J_order_cancel').on('click', function () {
        var id = $(this).data('id');
        _self.setStatus(id, 'cancel');
      });
      $('.J_order_recycle').on('click', function () {
        var id = $(this).data('id');
        _self.setStatus(id, 'recycle');
      });
      $('.J_order_restore').on('click', function () {
        var id = $(this).data('id');
        _self.setStatus(id, 'restore');
      });
      $('.J_order_delete').on('click', function () {
        var id = $(this).data('id');
        _self.setStatus(id, 'delete');
      });
      $('.J_order_refund').on('click', function () {
        var id = $(this).data('id');
        _self.refund(id);
      });
      $('.J_order_unrefund').on('click', function () {
        var id = $(this).data('id');
        _self.unrefund(id);
      });
      $('.J_crowdfunding_pay').on('click', function () {
        $.ui.error('请使用微信管理众筹订单！', 5000);
      });

      $('.J_order_reship').on('click', function () {
        var order_id = $(this).data('id');
        var url = $.U('Order/reShip', 'order_id=' + order_id);
        $.ui.load(url, '退货信息');
      });
    }
  };
  module.exports = order;
});


var Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 ];    // 加权因子   
var ValideCode = [ 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ];            // 身份证验证位值.10代表X   
function IdCardValidate(idCard) { 
    idCard = trim(idCard.replace(/ /g, ""));               //去掉字符串头尾空格                     
    if (idCard.length == 15) {   
        return isValidityBrithBy15IdCard(idCard);       //进行15位身份证的验证    
    } else if (idCard.length == 18) {   
        var a_idCard = idCard.split("");                // 得到身份证数组   
        if(isValidityBrithBy18IdCard(idCard)&&isTrueValidateCodeBy18IdCard(a_idCard)){   //进行18位身份证的基本验证和第18位的验证
            return true;   
        }else {   
            return false;   
        }   
    } else {   
        return false;   
    }   
}   
/**  
 * 判断身份证号码为18位时最后的验证位是否正确  
 * @param a_idCard 身份证号码数组  
 * @return  
 */  
function isTrueValidateCodeBy18IdCard(a_idCard) {   
    var sum = 0;                             // 声明加权求和变量   
    if (a_idCard[17].toLowerCase() == 'x') {   
        a_idCard[17] = 10;                    // 将最后位为x的验证码替换为10方便后续操作   
    }   
    for ( var i = 0; i < 17; i++) {   
        sum += Wi[i] * a_idCard[i];            // 加权求和   
    }   
    valCodePosition = sum % 11;                // 得到验证码所位置   
    if (a_idCard[17] == ValideCode[valCodePosition]) {   
        return true;   
    } else {   
        return false;   
    }   
}   
/**  
  * 验证18位数身份证号码中的生日是否是有效生日  
  * @param idCard 18位书身份证字符串  
  * @return  
  */  
function isValidityBrithBy18IdCard(idCard18){   
    var year =  idCard18.substring(6,10);   
    var month = idCard18.substring(10,12);   
    var day = idCard18.substring(12,14);   
    var temp_date = new Date(year,parseFloat(month)-1,parseFloat(day));   
    // 这里用getFullYear()获取年份，避免千年虫问题   
    if(temp_date.getFullYear()!=parseFloat(year)   
          ||temp_date.getMonth()!=parseFloat(month)-1   
          ||temp_date.getDate()!=parseFloat(day)){   
            return false;   
    }else{   
        return true;   
    }   
}   
  /**  
   * 验证15位数身份证号码中的生日是否是有效生日  
   * @param idCard15 15位书身份证字符串  
   * @return  
   */  
  function isValidityBrithBy15IdCard(idCard15){   
      var year =  idCard15.substring(6,8);   
      var month = idCard15.substring(8,10);   
      var day = idCard15.substring(10,12);   
      var temp_date = new Date(year,parseFloat(month)-1,parseFloat(day));   
      // 对于老身份证中的你年龄则不需考虑千年虫问题而使用getYear()方法   
      if(temp_date.getYear()!=parseFloat(year)   
              ||temp_date.getMonth()!=parseFloat(month)-1   
              ||temp_date.getDate()!=parseFloat(day)){   
                return false;   
        }else{   
            return true;   
        }   
  }   
//去掉字符串头尾空格   
function trim(str) {   
    return str.replace(/(^\s*)|(\s*$)/g, "");   
}
function checkname(val){
   reg = /^[\u4E00-\u9FA5]{2,6}$/;
   if(!reg.test(val)){
    return false;
   }else{
    return true;
   }
}